/* eslint-disable array-callback-return */

import React from 'react';
import { connect } from 'dva';
import { Divider, Steps } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import QuoUpload from './QuoUpload';
import { urlParse } from '@/utils/utils';

const { Step } = Steps;

@connect(({ quoupdate, quotation, publicdata, loading }) => ({
  quoupdate,
  uploading: loading.effects['publicdata/uploadFile'],
  batchQuery: quoupdate.batchQuery,
  isQuoChanged: quotation.isQuoChanged,
  fileId: publicdata.downloadFile.fileId,
  fileName: publicdata.downloadFile.fileName,
  nextData: quoupdate.nextData,
  cacheKey: quoupdate.getBatchId,

  currentStep: quoupdate.currentStep,
  progressPercent: quoupdate.progressPercent,
  resultInfo: quoupdate.resultInfo,
  showProgress: quoupdate.showProgress,
}))
class Batch extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isSubmit: false,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { batchAdjType, quoId, quoState } = urlParse(location.search);
    this.setState({
      quoId,
      quoState,
    });
    dispatch({
      type: 'quoupdate/updateQuery',
      payload: { batchAdjType, progressPercent: 0 },
    });
  }

  componentWillUnmount() {
    this.clearModel();
  }

  // 重置model
  clearModel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: {
        currentStep: 0,
        progressPercent: 0,
        showProgress: false,
        batchQuery: {
          // 批量上传数据
          sendType: '1',
          tempFlag: '1',
          isSerSetFlag: '1',
        },
      },
    });
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: { currentStep },
    });
    if (!currentStep) {
      dispatch({
        type: 'quoupdate/updateModelData',
        payload: {
          currentStep: 0,
          progressPercent: 0,
          showProgress: false,
        },
      });
    }
  };

  // 下一步
  onNext = () => {
    const {
      dispatch,
      batchQuery: { batchAdjType },
      currentStep,
    } = this.props;
    dispatch({
      type: 'quotation/getDownloadInfo',
      payload: {
        batchAdjType,
      },
    });
    this.setCurrentstep(currentStep + 1);
  };

  // 上传文件：需要携带参数即传：batchQuery
  uploadFile = formData => {
    const { cacheKey, dispatch, quoupdate } = this.props;
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: {
        resultInfo: {
          // 结果数据必传
          batchName: '', // 任务名称
          taskCount: 0, // 导入数据
          successCount: 0, // 成功数据
          errorCount: 0, // 失败数据
          batchNo: '', // 批次号
          errorUrl: '/csApi/batchAdj/export/error', // 下载错误信息地址
          errorParams: null, // 下载错误数据参数
          quoId: null,
          quoState: null,
        },
      },
    });
    const submitData = quoupdate.nextData;
    if (submitData && submitData.packList) {
      submitData.packList.map(packitem => {
        packitem.priceList.map(pritem => {
          const temp = pritem;
          temp.areaId = Array.isArray(pritem.areaId)
            ? pritem.areaId && pritem.areaId.join(',')
            : pritem.areaId;
        });
      });
    }

    // // 需要携带参数即传：batchQuery，不需要传参可省略
    const batchQuery = { cacheKey, packList: submitData.packList };
    Object.entries(batchQuery).forEach(([key, value]) => {
      let temp = value;
      if (key === 'packList') {
        temp = JSON.stringify(value);
      }
      formData.append(key, temp);
    });

    dispatch({
      type: 'quoupdate/uploadFileWithProgress',
      payload: formData,
    });
  };

  // 进度条模态框显隐
  handleModalVisible = flag => {
    const { dispatch } = this.props;
    if (!flag) {
      const batchQuery = { progressPercent: 0, sendType: '1', tempFlag: '1', isSerSetFlag: '1' };
      dispatch({
        type: 'quoupdate/updateQuery',
        payload: { batchQuery, progressPercent: 0 },
      });
    }
  };

  clearResultData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'quoupdate/updateModelData',
      payload: {
        resultInfo: {
          // 结果数据必传
          batchName: '', // 任务名称
          taskCount: 0, // 导入数据
          successCount: 0, // 成功数据
          errorCount: 0, // 失败数据
          batchNo: '', // 批次号
          errorUrl: '/csApi/batchAdj/export/error', // 下载错误信息地址
          errorParams: null, // 下载错误数据参数
          quoId: null,
          quoState: null,
        },
      },
    });
  };

  render() {
    const {
      fileId,
      fileName,
      uploading,
      isQuoChanged,
      currentStep,
      showProgress,
      progressPercent,
      resultInfo,
    } = this.props;
    const { isSubmit, quoId, quoState } = this.state;
    const isExactDiv = () => (
      <div style={{ marginTop: 50 }}>
        <p style={{ margin: '0 auto', width: '90%', fontSize: 14, textAlign: 'left' }}>
          说明：
          <br />
          1、生效日期默认当月；
          <br />
          2、<span style={{ color: '#000' }}>增加产品</span>
          的业务开始年月以及其他属性通过上传文件补充，人员状态是已离职或离职办理中的可不填写，其他状态的必需填写，如果只是部分在职人员增加产品，只能通过更换报价单实现；
          <br />
          3、<span style={{ color: '#000' }}>减少产品</span>
          可分别填写结束日期，如果减少社保或公积金需要填写停做原因，如果填写结束日期不满足减员截止日要求，会自动后延；
          <br />
          4、<span style={{ color: '#000' }}>属性变更</span>针对报价单下已有人员
          <span style={{ color: '#f90' }}>无影响</span>
          ，只对修改之后再增员的人员有效，如需修改已有人员可通过调整功能进行修改。
          <Divider />
          {isQuoChanged && <h3>变更人员信息</h3>}
        </p>
      </div>
    );
    return (
      <PageHeaderWrapper>
        <div style={{ padding: '16px 24px 50px 24px', background: '#fff' }}>
          <Steps current={2} style={{ marginBottom: 70 }}>
            <Step title="选择产品" />
            <Step title="设置价格" />
            <Step title="人员信息" />
            <Step title="完成" />
          </Steps>

          <QuoUpload
            {...this.props}
            currentStep={currentStep}
            setCurrentstep={this.setCurrentstep}
            isQuoChanged={isQuoChanged}
            downloadTempInfo={{
              // 下载模板信息
              params: { fileId, fileName },
              url: '/csApi/batchTask/downloadFile',
            }}
            uploadFile={this.uploadFile}
            uploading={uploading}
            // 展示进度条需要的数据
            maskClosable
            progressTitle={resultInfo.batchName || '正在提交'}
            progressPercent={progressPercent || 0}
            progressVisible={showProgress}
            handleModalVisible={this.handleModalVisible}
            clearResultData={this.clearResultData}
            isExact={isExactDiv}
            preStep={() => {
              this.setCurrentstep(currentStep - 1);
              router.push(
                `/salemanage/quotation/updatesetprice?quoId=${quoId}&quoState=${quoState}&preInfo=true`
              );
            }}
            isSubmit={isSubmit}
          />
        </div>
      </PageHeaderWrapper>
    );
  }
}

export default Batch;
